﻿using LiteBlog.IoC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;

namespace LiteBlog.Infrastructure
{
    public class CustomControllerFactory : IControllerFactory
    {
        private static readonly string ControllerTypeTemplate = "LiteBlog.Controllers.Contracts.I{0}Controller, LiteBlog.Controllers";
        private static readonly string DefaultControllerName = "LiteBlog.Controllers.Contracts.IHomeController, LiteBlog.Controllers";

        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            string controllerTypeName = string.Format(ControllerTypeTemplate, controllerName);
            var controllerType = Type.GetType(controllerTypeName, false, true) ?? Type.GetType(DefaultControllerName, false, true);
            
            // Set the action invoker!
            var controller = (Controller)IoCContainer.Resolve(controllerType);
            controller.ActionInvoker = new CustomActionInvoker();
            return controller;
        }

        public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
        {
            return SessionStateBehavior.Default;
        }

        public void ReleaseController(IController controller)
        {
        }
    }
}